package component;

import Main.Main;
import ui.HomePage;
import util.FileUtils;
import util.GsonUils;
import util.ImageUtils;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.List;

/**
 * @author zhongwen
 * @description 类选项卡
 * @date 2021-12-22 11:00
 */
public class ClassTab extends JPanel {
    public static int sum = 0;
    private TablePane tablePane;
    private JLabel jLabel = new JLabel();
    /**
     * 选项卡所对应的文件名，在二次保存的时候起作用
     */
    private File textFile = null;

    public ClassTab(TablePane tablePane) {
        ClassTab.sum++;
        this.tablePane = tablePane;
        setLayout(new BorderLayout());
        setBorder(null);
        Box horizontalBox = Box.createHorizontalBox();
        jLabel.setText("untitled" + ClassTab.sum);
        jLabel.setIcon(new ImageIcon(ImageUtils.getImage("class.png", 18, 18)));
        horizontalBox.add(jLabel);
        horizontalBox.add(Box.createHorizontalStrut(5));
        horizontalBox.add(new CloseButton());
        this.add(horizontalBox, BorderLayout.CENTER);
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                // 点击选项卡，切换面板
                tablePane.setSelectedIndex(tablePane.indexOfTabComponent(ClassTab.this));
                System.out.println("点击了包容选项卡的面板");
            }
        });

    }


    // 修改选项卡上的文件名称
    public void changeFileName(String name) {
        jLabel.setText(name);
    }


    public String getFileName() {
        return jLabel.getText();
    }


    public void setTextFile(File textFile) {
        this.textFile = textFile;
    }

    public File getTextFile() {
        return textFile;
    }

    /**
     * 文件关闭时提示是否要保存文件
     */
    public void needSaveFile() {
        // 带后缀名过滤器
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Java源文件(*.java)", "java");

        int index = tablePane.indexOfTabComponent(this);
        JavaEditorPane pane = (JavaEditorPane) tablePane.getComponentAt(index);
        String nowText = pane.getTextArea().getText();
        // nowText初始为一行空
        if (this.getTextFile() == null && nowText.length() > 0) {
            int i = JOptionPane.showConfirmDialog(HomePage.jf,"是否保存对" + "\"" +
                    this.getFileName() + "\"" + "文件的更改", "CodeEasy", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null);
            if(i == JOptionPane.YES_OPTION){
                JFileChooser saveFile = new JFileChooser(Main.configurationBean.getNowPath()) {
                    @Override
                    public void approveSelection() {
                        File selectedFile = this.getSelectedFile();
                        if(selectedFile != null){
                            String name = selectedFile.getName();
                            if (!name.contains(".java") && this.getFileFilter().equals(filter)) {
                                selectedFile = new File(this.getCurrentDirectory() + name + ".java");
                                name = selectedFile.getName();
                            } else {
                                selectedFile = new File(this.getCurrentDirectory() + name);
                                name = selectedFile.getName();
                            }
                            if (selectedFile.exists()) {
                                int i = JOptionPane.showConfirmDialog(HomePage.jf, "是否保存对" + "\"" +
                                        selectedFile.getAbsolutePath() + "\"" + "文件的更改", "CodeEasy", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null);
                                if (i == JOptionPane.YES_OPTION) {
                                    FileUtils.saveFile(getSelectedFile(), nowText, BottomBar.encodeButton.getText());
                                    ClassTab.this.changeFileName(name);
                                    ClassTab.this.setTextFile(selectedFile);
                                    super.approveSelection();
                                }
                            } else {
                                super.approveSelection();
                            }
                        }
                    }
                };
                saveFile.setFileFilter(filter);
                // 设置默认的文件名
                String name = FileUtils.getDefaultName(nowText);
                System.out.println("需保存文件的默认名字 ： " + name);
                if (name != null) {
                    saveFile.setSelectedFile(new File(name));
                }
                else{
                    saveFile.setSelectedFile(new File(this.getFileName()));
                }
                saveFile.showSaveDialog(HomePage.jf);

                // 将修改的默认打开文件目录保存到配置文件中
                Main.configurationBean.setNowPath(saveFile.getCurrentDirectory().toString());
                GsonUils.objectToString(Main.configurationBean);
            }
        }
        else if(getTextFile() != null){
            String encoding = FileUtils.getFileEncode(getTextFile());
            List<String> temp = FileUtils.openFilesWithList(getTextFile(), encoding);
            StringBuilder openFileString = new StringBuilder();
            for(int i = 0; i < temp.size() - 1; i++){
                openFileString.append(temp.get(i) + "\n");
            }
            if(temp.size() > 0){
                openFileString.append(temp.get(temp.size() - 1));
            }
            String tempString = openFileString + "\n";
            if (!openFileString.toString().equals(nowText) && !tempString.equals(nowText)) {
                /*System.out.println("不匹配");
                System.out.println(nowText);
                System.out.println("*******************");
                System.out.println(openFileString);
                System.out.println("**********************");*/
                int i = JOptionPane.showConfirmDialog(HomePage.jf, "是否保存对" + "\"" +
                        this.getTextFile().getAbsolutePath() + "\"" + "文件的更改", "CodeEasy", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null);
                if(i == JOptionPane.YES_OPTION){
                    FileUtils.saveFile(getTextFile(), nowText, BottomBar.encodeButton.getText());
                }
            }
        }
    }

    class CloseButton extends JButton {
        public CloseButton() {
            this.setFont(new Font("宋体", Font.PLAIN, 16));
            this.setText("x");
            this.setBorder(null);
            this.setToolTipText("close " + ClassTab.this.getFileName() +  ".java");
            this.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    super.mouseClicked(e);
                    int index = tablePane.indexOfTabComponent(ClassTab.this);
                    System.out.println(index + "当前选项卡页");
                    needSaveFile();
                    if (index != -1) {
                        tablePane.removeClass(index);
                    }
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    CloseButton.this.setBorderPainted(true);
                    CloseButton.this.setForeground(Color.cyan);
                    super.mouseEntered(e);
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    CloseButton.this.setBorderPainted(false);
                    CloseButton.this.setForeground(Color.BLACK);
                    super.mouseExited(e);
                }
            });
        }
    }

}
